package com.cskaoyan.market.controller.admin;

import com.cskaoyan.market.db.domain.MarketAd;
import com.cskaoyan.market.service.MarketAdService;
import com.cskaoyan.market.service.impl.MarketAdServiceImpl;
import com.cskaoyan.market.util.GetRequestBodyUtil;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@RestController
@RequestMapping("admin/ad")
public class AdminAdController {
    @Autowired
    MarketAdService marketAdService;

    @GetMapping("list")
    private Object list(String page,String limit,String name,String sort,String order, String content) throws IOException {
        //name、content不是必须的请求参数，可能为null
        if (name == null) {
            name = "";
        }
        if (content == null) {
            content = "";
        }
        List<MarketAd> marketAds = marketAdService.list(page, limit, name, content, sort, order);
        System.out.println(marketAds.get(0));
        Object o = ResponseUtil.okList(marketAds);
        return o;
    }

    @PostMapping("update")
    private Object update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = GetRequestBodyUtil.getRequestBody(req);
        //将请求体中Json格式的字符串转换成对应修改条件的广告实体类
        MarketAd ad = JacksonUtil.getObjectMapper().readValue(requestBody, MarketAd.class);
        MarketAd marketAd = marketAdService.update(ad);
        return ResponseUtil.ok(marketAd);
    }

    @PostMapping("create")
    private Object create(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = GetRequestBodyUtil.getRequestBody(req);
        MarketAd marketAd = JacksonUtil.getObjectMapper().readValue(requestBody, MarketAd.class);
        MarketAd InsertedMarketAd = marketAdService.createAd(marketAd);
        return ResponseUtil.ok(InsertedMarketAd);
    }

    @PostMapping("delete")
    private Object delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = GetRequestBodyUtil.getRequestBody(req);
//        将请求体中Json字符串中的id的value解析成字符串
        String id = JacksonUtil.parseString(requestBody, "id");
        marketAdService.deleteAd(id);
        return ResponseUtil.ok();
    }

}
